#ifndef CHATSERVICE_H
#define CHATSERVICE_H

#include <muduo/net/TcpConnection.h>
#include "json.hpp"
#include <unordered_map>
#include <mutex>
#include "usermodel.hpp"
#include "offlinemessagemodel.hpp"
#include "friendmodel.hpp"
#include "groupmodel.hpp"
#include "redis.hpp"

using namespace std;
using namespace muduo;
using namespace muduo::net;

using json = nlohmann::json;

using MsgHandler = std::function<void(const TcpConnectionPtr &conn, json &js, Timestamp)>;

//聊天服务类，用于执行请求类型所对应的任务
class ChatService
{
public:
    static ChatService* instance();
    void login(const TcpConnectionPtr &conn, json &js, Timestamp);
    void reg(const TcpConnectionPtr &conn, json &js, Timestamp);
    void connCloseException(const TcpConnectionPtr &conn);
    void oneChat(const TcpConnectionPtr &conn, json &js, Timestamp);
    void reset();
    void addFriend(const TcpConnectionPtr &conn, json &js, Timestamp);
    void createGroup(const TcpConnectionPtr &conn, json &js, Timestamp);
    void addGroup(const TcpConnectionPtr &conn, json &js, Timestamp);
    void chatGroup(const TcpConnectionPtr &conn, json &js, Timestamp);
    void exitProcess(const TcpConnectionPtr &conn, json &js, Timestamp);
    void handleRedisSubscribeMessage(int userid, string msg);
    MsgHandler getHandler(int msgid);
private:
    ChatService();

    UserModel um_;
    OfflineMessageModel offlineMsgModel_;
    FriendModel friendModel_;
    GroupModel groupModel_;
    unordered_map<int, MsgHandler> msgHandlerMap_;

    Redis redis_;

    mutex connMtx_;
    unordered_map<int, TcpConnectionPtr> connMap_;
};
#endif